package com.xxg.renrenproduct.dao;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Indexes;
import com.xxg.renrencommon.domain.bean.ProductGatherInfo;
import org.bson.Document;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.Date;

import static org.springframework.data.mongodb.core.query.Criteria.where;

/**
 * 商品采集信息dao
 *
 * @author szj
 * @date 2021/11/29
 */
@Repository
public class ProductGatherInfoDao {
    private final MongoTemplate mongoTemplate;

    public ProductGatherInfoDao(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
        createCollection();
    }

    /**
     * 创建collection
     */
    private void createCollection() {
        String collectionName = "productGatherInfo";
        MongoCollection<Document> collection;
        if (!mongoTemplate.getCollectionNames().contains(collectionName)) {
            collection = mongoTemplate.createCollection(ProductGatherInfo.class);
            createIndex(collection);
        }
    }

    /**
     * 创建索引
     *
     * @param collection 数据集
     */
    private void createIndex(MongoCollection<Document> collection) {
        collection.createIndex(Indexes.ascending("userId"));
        collection.createIndex(Indexes.ascending("shopId"));
        collection.createIndex(Indexes.ascending("spuId"));
        collection.createIndex(Indexes.compoundIndex(Indexes.ascending("spuId"), Indexes.ascending("userId")));
    }

    public ProductGatherInfo findByUserIdAndSpuId(Integer userId, Integer spuId) {
        Query query = new Query(where("userId").is(userId).and("spuId").is(spuId));
        return mongoTemplate.findOne(query, ProductGatherInfo.class);
    }

    public void insert(ProductGatherInfo productGatherInfo) {
        productGatherInfo.setCreateTime(new Date());
        productGatherInfo.setUpdateTime(new Date());
        mongoTemplate.insert(productGatherInfo);
    }
}
